<script setup>
import PageContainer from '@/components/pageContainer.vue'
import { onMounted, ref } from 'vue'
import { editFoodStatusService, getFoodListService } from '@/api/food/food'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  deleteFoodService,
  updateFoodService,
  getFoodById
} from '@/api/food/food'
import { getCategoryListService } from '../../api/category/category'
import { ElTable } from 'element-plus'

const page = ref(1)
const pageSize = ref(8)
const total = ref(0)
const foodName = ref('')
const foodList = ref([])
const queryParams = ref({
  page: 1,
  pageSize: 8,
  name: null
})
const changeFoodStatus = async (scope) => {
  // const ids = ref([])
  // ids.value.push(scope.row.id)
  const data = {
    status: scope.row.status,
    ids: scope.row.id
  }
  const res = await editFoodStatusService(data)
  if (res.data.code === 1) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.error(res.data.msg)
  }
}

const getFoodList = async () => {
  console.log('query', queryParams.value.name)
  const res = await getFoodListService(queryParams.value)
  console.log('res', res.data.data)
  foodList.value = res.data.data.records
  total.value = res.data.data.total
}
const dialogVisible = ref(false)
const title = ref('')
const formRef = ref(null)
const formModel = ref({})
const typeList = ref([])
const addFoodHandle = () => {
  title.value = '添加食物'
  if (formRef.value) {
    formRef.value.clearValidate()
  }
  dialogVisible.value = true
}
const handleBeforeClose = () => {
  dialogVisible.value = false
  formModel.value = {}
  getFoodList()
}

// 编辑
const editFood = async (row) => {
  const res = await getFoodById(row)
  console.log(res.data.data)
  formModel.value = res.data.data
  const data = {
    page: page.value,
    pageSize: pageSize.value
  }
  const test = await getCategoryListService(data)
  // console.log(test.data.data.records)
  typeList.value = test.data.data.records
  dialogVisible.value = true
}
// 保存
const handleSubmit = async () => {
  console.log(6666, formModel)
  if (formModel.value.foodType === 1) params.foodType = 'grains'
  else if (formModel.value.foodType === 2) params.foodType = 'vegetable'
  else if (formModel.value.foodType === 3) params.foodType = 'meat'
  else if (formModel.value.foodType === 4) params.foodType = 'fruit'
  else if (formModel.value.foodType === 5) params.foodType = 'milkGroup'
  else if (formModel.value.foodType === 6) params.foodType = 'grease'
  else formModel.value.foodType = 'other'
  const res = await updateFoodService(formModel.value)
  if (res.data.code === 1) {
    ElMessage.success('修改成功')
  } else {
    ElMessage.error(res.data.msg)
  }
  dialogVisible.value = false
  await getFoodList()
  console.log(res)
}
//获取选中的行
const selects = ref(null)
const handleSelectionChange = (selection) => {
  if (selection.length === 0) {
    selects.value = null
    return
  }
  selects.value = selection
}
//删除
const deleteHandle = (type, id) => {
  console.log('selects', selects.value)
  if (type === -1)
    if (!selects.value) {
      ElMessage({
        message: '请选择要删除的食物',
        type: 'warning'
      })
      return
    }
  ElMessageBox.confirm('你确认删除所选食物吗?', '提示', {
    customClass: 'el-message-box-myself',
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'ElMessageBox-confirm-button-style',
    cancelButtonClass: 'ElMessageBox-cancel-button-style'
  })
    .then(async () => {
      const ids = []
      if (type === -1)
        selects.value.map((item) => {
          console.log('id', item.id)
          ids.push(item.id)
          console.log('ids', ids)
        })
      else ids.push(id)
      try {
        const res = await deleteFoodService(ids.join(','))
        console.log('res', res)

        if (res.data.code === 1) {
          ElMessage({
            type: 'success',
            message: '删除成功'
          })
        } else {
          ElMessage.error(res.data.msg || '操作失败')
        }

        await getFoodList()
      } catch (e) {
        console.log('请求出错了：' + e)
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除'
      })
    })
}
const handleQuery = () => {
  queryParams.value.page = 1
  getFoodList()
}
const resetForm = () => {
  queryParams.value.name = null
  handleQuery()
}
onMounted(() => {
  getFoodList()
})
</script>

<template>
  <el-dialog
    style="border-radius: 25px"
    v-model="dialogVisible"
    width="25%"
    :title="title"
    :modal="true"
    :before-close="handleBeforeClose"
  >
    <el-form
      :label-position="'right'"
      :model="formModel"
      :rules="rules"
      ref="formRef"
    >
      <el-row :gutter="10" justify="space-between">
        <el-col :span="12">
          <el-form-item label="名称" prop="username">
            <el-input v-model="formModel.name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类" prop="name">
            <el-select
              v-model="formModel.foodType"
              class="m-2"
              placeholder="选择食物分类"
            >
              <el-option
                v-for="(item, index) in typeList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="能量" prop="phone">
            <el-input v-model="formModel.energy"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="碳水" prop="idNumber">
            <el-input v-model="formModel.carbohydrate"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="蛋白质" prop="username">
            <el-input v-model="formModel.protein"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="脂肪" prop="name">
            <el-input v-model="formModel.fat"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <div style="position: absolute; right: 0; margin-top: 30px">
          <el-button
            color="#8fbc8f"
            type="primary"
            plain
            round
            @click="handleSubmit()"
            >确定
          </el-button>
          <el-button type="info" plain round @click="handleBeforeClose"
            >取消
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>

  <div class="floating-box">
    <div>
      <el-form
        :model="queryParams"
        ref="queryRef"
        :inline="true"
        label-width="68px"
        class="no-wrap"
        @keydown.enter.prevent
      >
        <el-form-item label="食物名称" prop="name">
          <el-input
            prefix-icon="Search"
            v-model="queryParams.name"
            placeholder="请输入食物名称"
            style="width: 200px"
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item>
          <div class="no-wrap">
            <el-button
              icon="Search"
              plain
              round
              color="#95d475"
              @click="handleQuery()"
              >搜索</el-button
            >
            <el-button
              icon="Refresh"
              plain
              round
              color="#95d475"
              @click="resetForm()"
              >重置</el-button
            >
            <el-button
              icon="CirclePlus"
              plain
              round
              color="#95d475"
              @click="addFoodHandle()"
              >添加食物</el-button
            >
            <el-button
              icon="Delete"
              plain
              round
              color="#95d475"
              @click="deleteHandle(-1, null)"
              >批量删除</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <el-divider />
    </div>

    <el-table
      :data="foodList"
      width="100%"
      :stripe="true"
      size="large"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="45" />
      <el-table-column
        label="食物名称"
        prop="name"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="食物分类"
        prop="foodType"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="能量"
        prop="energy"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="碳水"
        prop="carbohydrate"
        align="center"
      ></el-table-column>
      <el-table-column
        label="蛋白质"
        prop="protein"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="脂肪"
        prop="fat"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="状态" prop="" align="center">
        <template #default="scope">
          <el-switch
            @change="changeFoodStatus(scope)"
            v-model="scope.row.status"
            inline-prompt
            active-text="正常"
            :active-value="1"
            style="--el-switch-on-color: #8fbc8f"
            :inactive-value="0"
            inactive-text="禁用"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="最后修改时间"
        prop="updateTime"
        align="center"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column label="操作" align="center" width="210">
        <template #default="{ row }">
          <div class="no-wrap">
            <el-button
              type="primary"
              color="#8fbc8f"
              plain
              round
              icon="Edit"
              @click="editFood(row)"
              >编辑
            </el-button>
            <el-button
              type="info"
              plain
              round
              icon="Delete"
              @click="deleteHandle(0, row.id)"
              >删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.page"
        v-model:page-size="queryParams.pageSize"
        layout="total, prev, pager, next, jumper"
        v-show="total > 0"
        :total="total"
        @size-change="getFoodList"
        @current-change="getFoodList"
      />
    </div>
  </div>
</template>

<style scoped>
/deep/ .el-input__wrapper {
  border-radius: 50px;
  /*background-color: red;*/
}
</style>
